//
//  PKLoginViewModal.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/8.
//

import Foundation
import RxSwift
import RxCocoa
import UIKit
import Moya
import AuthenticationServices
class PKLoginViewModal : NSObject {
    let email = BehaviorRelay(value: "")
    let password = BehaviorRelay(value: "")
    let errorTracker = ErrorTracker()
    
    let isLoginButtonEnabled : Observable<Bool>
    private let provider = MoyaProvider<APIService>(stubClosure: MoyaProvider.immediatelyStub)
    
    let signInAppleTapped = PublishSubject<Void>()
    let userInfo = PublishSubject<ASAuthorizationAppleIDCredential>()
    let error = PublishSubject<Error>()
//    override init() {
//        
//    }
    private func setupBinding() {
          signInAppleTapped
              .subscribe(onNext: { [weak self] in
                  self?.performAppleSignIn()
              })
              .disposed(by: rx.disposeBag)
      }
      
      private func performAppleSignIn() {
          let request = ASAuthorizationAppleIDProvider().createRequest()
          request.requestedScopes = [.fullName, .email]
          
          let controller = ASAuthorizationController(authorizationRequests: [request])
          controller.delegate = self
          controller.presentationContextProvider = self
          controller.performRequests()
      }
    
    init(isLoginButtonEnabled: Observable<Bool>) {
        self.isLoginButtonEnabled = Observable.combineLatest(email.asObservable(),password.asObservable()){ email, password in
            return !email.isEmpty && password.count >= 6
        }.distinctUntilChanged()
    }
    
    func login() -> Observable<Bool>{
        return provider.rx.request(.login(username: email.value, password: password.value)).map{ response in
            return response.statusCode == 200
        }.asObservable().trackError(errorTracker)
    }
    
    
    
}
extension PKLoginViewModal: ASAuthorizationControllerDelegate {
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let credential = authorization.credential as? ASAuthorizationAppleIDCredential {
           
            if let tokenData = credential.identityToken,let tokenString = String(data: tokenData,encoding: .utf8){
                ///发送tokenString给服务器进行验证
                userInfo.onNext(credential)
                
            }
        }
    }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        self.error.onNext(error)
    }
}

extension PKLoginViewModal: ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        // 可由外部注入 window，如需更灵活控制
        return UIApplication.shared.windows.first { $0.isKeyWindow } ?? UIWindow()
    }
}
